package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.entity.User;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;

/**
 * @author GL160601@163.com
 * @date 2020/12/16 14:24
 */

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Override
    public Boolean dataIsExists(String data, Integer type) {
        //方法一
//        if (type != 1 && type != 2) {
//            throw new LyException(400, "请求参数有误!");
//        }
//        return query()
//                .eq(type == 1, "username", data)
//                .eq(type == 2, "phone", data)
//                .count() == 1;

        String colName = null;
        switch (type) {
            case 1:
                colName = "username";
                if (StringUtils.isNotEmpty(data)) {
                    throw new LyException(400, "请求参数有误!");
                }
                break;
            case 2:
                colName = "phone";
                if (!RegexUtils.isPhone(data)) {
                    throw new LyException(400, "查询参数有误!");
                }
                break;
            default:
                throw new LyException(400, "查询参数有误!");
        }
        return query().eq(colName, data).count() == 1;
    }


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AmqpTemplate amqpTemplate;

    private final String KEY_PREFIX = "ly.user.verify";

    @Override
    public void SendMsg(String phone) {
        if (!RegexUtils.isPhone(phone)) {
            throw new LyException(400, "请求参数有误!");
        }

        //将手机号和验证码放入map中
        Map<String, String> msg = new HashMap<>();

        //使用Apache的工具生成6位数验证码
        String code = RandomStringUtils.randomNumeric(6);
        msg.put("phone", phone);
        msg.put("code", code);

        //消息发送
        //参数1:消息服务交换机名称
        //参数2:商品下架的routing-key
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME, VERIFY_CODE_KEY, msg);

        //存入redis要加入业务前缀来区分业务
        String key = KEY_PREFIX + phone;
        this.redisTemplate.opsForValue().set(key, code, 5, TimeUnit.MINUTES);
    }



    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Transactional
    @Override
    public void registUser(User user, String code) {
        String key = KEY_PREFIX + user.getPhone();
        //redisTemplate.opsForValue().get(key))  通过手机号key取得验证号码value
        if (StringUtils.isEmpty(code) || !code.equals(redisTemplate.opsForValue().get(key))) {
            throw new LyException(400, "验证码有误!");
        }

        //对密码进行加密,生成随机盐值,优点:颜值不外漏
        String encodePassword = passwordEncoder.encode(user.getPassword());

        user.setPassword(encodePassword);

        this.save(user);
    }


    @Override
    public UserDTO queryUser(String username, String password) {
        User user = this.query()
                .eq("username", username)
                .one();

        if (user == null) {
            throw new LyException(400, "用户不存在!");
        }

        //passwordEncoder.matches()  解密
        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new LyException(400, "密码错误!");
        }
        return new UserDTO(user);
    }

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public UserDetail checkLogin(String token) {
        Payload payload = jwtUtils.parseJwt(token);

        UserDetail userDetail = payload.getUserDetail();

        return userDetail;

    }
}
